package com.project.srtp.secure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.srtp.secure.dao.entity.InitKeyDO;
import com.project.srtp.secure.dao.mapper.InitKeyMapper;
import com.project.srtp.secure.service.InitKeyService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 曹行阳
 * @version 0.1
 * @date 2025/6/16 12:50
 */
@Service
public class InitKeyServiceImpl extends ServiceImpl<InitKeyMapper, InitKeyDO> implements InitKeyService {
    @Override
    @Transactional
    public void storeInitKey(InitKeyDO initKeyDO) {
        // 先查是否已存在
        LambdaQueryWrapper<InitKeyDO> queryWrapper = Wrappers.lambdaQuery(InitKeyDO.class)
                .eq(InitKeyDO::getUserId, initKeyDO.getUserId());

        InitKeyDO existing = baseMapper.selectOne(queryWrapper);

        if (existing != null) {
            // 存在就更新（保留主键 ID）
            initKeyDO.setId(existing.getId());
            boolean success = this.updateById(initKeyDO);
            if (!success) {
                throw new RuntimeException("更新初始化密钥失败");
            }
        } else {
            // 不存在则插入
            try {
                boolean success = this.save(initKeyDO);
                if (!success) {
                    throw new RuntimeException("插入初始化密钥失败");
                }
            } catch (DuplicateKeyException ex) {
                // 出现主键冲突说明并发插入导致重复，可以忽略或再次查一遍
                log.error("并发插入 InitKey 发生冲突，尝试忽略", ex);
            }
        }
    }


    @Override
    public InitKeyDO selectInitKeyByUserId(String userId) {
        LambdaQueryWrapper<InitKeyDO> queryWrapper = Wrappers.lambdaQuery(InitKeyDO.class)
                .eq(InitKeyDO::getUserId, userId);
        try {
            return baseMapper.selectOne(queryWrapper);
        } catch (Exception e) {
            log.error("用户不存在");
        }
        return null;
    }
}
